package lock;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Classname PrintByReentrantLockAndCondition
 * @Description   是用ReentrantLock和Condition的好处，使用方式是类似synchronized的使用，
 * 但是对比仅仅使用ReentrantLock的是时候，会防止ReentrantLock出现cpu空转的现象
 * @Date 2020/2/16 11:29 下午
 * @Created by gule
 */
public class PrintByReentrantLockAndCondition {
    private static Integer count = 0;
    private static boolean flag = true;
    private static Integer defaultValue = 200;
    private static ReentrantLock lock = new ReentrantLock(false);
    private static Condition condition1 = lock.newCondition();
    private static Condition condition2 = lock.newCondition();

    public static void main(String[] args) {

        ExecutorService executorService = new ThreadPoolExecutor(2, 4,
                1, TimeUnit.SECONDS,
                new LinkedBlockingDeque<>(10));
        executorService.execute(()->{
                while (count < defaultValue) {
                    lock.lock();
                    if (flag) {
                        System.out.println(Thread.currentThread().getName() + "偶数 num is " + count);
                        count++;
                        flag = false;
                    }
                    condition1.signalAll();
                    try {
                        condition1.await();
                    } catch (InterruptedException e) {
                        System.out.println("wait 异常");
                    }
                    lock.unlock();
                }
        });
        executorService.execute(()->{
                while (count < defaultValue) {
                    lock.lock();
                    if (!flag) {
                        System.out.println(Thread.currentThread().getName() + "奇数 num is " + count);
                        count++;
                        flag = true;
                    }
                    condition1.signalAll();
                    try {
                        condition1.await();
                    } catch (InterruptedException e) {
                        System.out.println("wait 异常");
                    }
                    lock.unlock();
                }
        });
    }
}
